var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var debug = require("debug");
var fs = require("fs");
var http = require('http');
var wechat_message = require('./routes/wechat_message');
var wechat_get = require('./routes/wechat_get');
var index = require('./routes/index');
var chat = require("./routes/chat");

var app = express();

//view引擎配置
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

//没配favicon.ico
//app.use(favicon(__dirname + '/public/favicon.ico'));

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//预处理，打印日志
app.use(function (req, res, next) {

    debug("HEADER " + JSON.stringify(req.headers));


    xml = '';
    req.on('data', function (chunk) {
        xml += chunk;
    });

    req.on('end', function () {
        console.log(xml);
    });
    next();
});

//配置路由
app.use('/',index);
app.post('/wechat', wechat_message);
app.get('/wechat',wechat_get);
app.use('/index', index);
app.use("/chat", chat);



// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

/**
 * Get port from environment and store in Express.
 */
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);


/**
 * Create HTTP server.
 */
var server = http.createServer(app);

//创建socket.io服务
var io = require('socket.io')(server);
io.on('connection', function (socket) {
    console.log('a user connected');

    socket.broadcast.emit('broadcast message', {"author":"system","text":'a new user connected'});

    socket.on('disconnect',function(){
        socket.broadcast.emit('broadcast message', {"author":"system","text":'a user disconnected'});
    });

    socket.on('broadcast info',function(msg){
        socket.broadcast.emit('broadcast info', msg);
    });

    socket.on('put message', function (msg) {

        socket.broadcast.emit('broadcast message', msg);

        fs.exists('comments.json', function (exists) {
            if(exists){
                fs.readFile('comments.json', function (err, data) {
                    var comments = JSON.parse(data);
                    comments.push(msg);
                    fs.writeFile('comments.json', JSON.stringify(comments, null, 4), function (err) {
                    if (err) throw err;
                    });
                });
            }else{
                comments = [];
                comments.push(msg);
                fs.writeFile('comments.json', JSON.stringify(comments, null, 4), function (err) {
                    if (err) throw err;
                });
            }
        });

        });



    socket.on('get message',function(msg){

        fs.exists('comments.json', function (exists) {
            if(exists){
                fs.readFile('comments.json', function (err, data) {
                    if (err) throw err;
                    socket.emit('get message',JSON.parse(data));

                });
            }
        });

    })

});


/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
    var port = parseInt(val, 10);

    if (isNaN(port)) {
        // named pipe
        return val;
    }

    if (port >= 0) {
        // port number
        return port;
    }

    return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
    if (error.syscall !== 'listen') {
        throw error;
    }

    var bind = typeof port === 'string'
        ? 'Pipe ' + port
        : 'Port ' + port;

    // handle specific listen errors with friendly messages
    switch (error.code) {
        case 'EACCES':
            console.error(bind + ' requires elevated privileges');
            process.exit(1);
            break;
        case 'EADDRINUSE':
            console.error(bind + ' is already in use');
            process.exit(1);
            break;
        default:
            throw error;
    }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
    var addr = server.address();
    var bind = typeof addr === 'string'
        ? 'pipe ' + addr
        : 'port ' + addr.port;
    debug('Listening on ' + bind);
    console.log("server started at port:" + port);
}